package cn.yuanqiao.archive.appManager.service.impl;

import cn.yuanqiao.archive.appManager.domain.*;
import cn.yuanqiao.archive.appManager.mapper.*;
import cn.yuanqiao.archive.appManager.service.ITenantCateMdataListService;
import cn.yuanqiao.archive.wenjianzhengli.domain.TenantTablehead;
import cn.yuanqiao.archive.wenjianzhengli.mapper.WenjianhuishouzhanMapper;
import cn.yuanqiao.common.config.YqDatabaseIdProvider;
import cn.yuanqiao.common.enums.DbIdEnum;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.PageUtils;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.sql.YqDatabaseSQLUtil;
import cn.yuanqiao.common.utils.SecurityUtils;
import com.alibaba.fastjson2.JSONObject;
import cn.yuanqiao.common.config.YqDatabaseIdProvider;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;

/**
 * 元数据明细Service业务层处理
 *
 * @author yuanqiao
 * @date 2023-06-09
 */
@Service
public class TenantCateMdataListServiceImpl implements ITenantCateMdataListService
{
    @Autowired
    private TenantCateMdataListMapper tenantCateMdataListMapper;
    @Autowired
    private TenantFieldsMapper tenantFieldsMapper;
    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;
    @Autowired
    private TenantCategoryServiceImpl tenantCategoryService;
    @Autowired
    private TenantMdataGroupMapper groupMapper;
    @Autowired
    private DataSource dataSource;

    @Autowired
    private YqDatabaseIdProvider yqDatabaseIdProvider;
    @Autowired
    private TenantApplyMapper tenantApplyMapper;
    @Autowired
    private WenjianhuishouzhanMapper wenjianhuishouzhanmapper;
    @Resource
    private SqlSessionFactory sqlSessionFactory;

    /**
     * 查询元数据明细
     *
     * @param id 元数据明细主键
     * @return 元数据明细
     */
    @Override
    public TenantMdataList selectYqdaMdataListById(Long id)
    {
        TenantMdataList tenantMdataList = new TenantMdataList();
        String tableName = tenantMdataList.getTableName();
        return tenantCateMdataListMapper.selectTenantMdataListById(id,tableName);
    }

    @Override
    public Map<String, Object> selectYqdaMdataListByIdAll(Long id) {
        Map<String, Object> map = new HashMap<>();
        TenantMdataList tenantMdataList = new TenantMdataList();
        String tableName = tenantMdataList.getTableName();
        map.put("HddaMDataList", tenantCateMdataListMapper.selectTenantMdataListById(id,tableName));
        //map.put("HdListRelatedelement",relatedelementMapper.selectHdListRelatedelementByMListId(id));
        //map.put("HdListSubelement",subelementMapper.selectHdListSubelementByMListId(id));
        return map;
    }

    /**
     * 查询元数据明细列表
     *
     * @param yqdaMdataList 元数据明细
     * @return 元数据明细
     */
    @Override
    public List<TenantMdataList> selectYqdaMdataListList(TenantMdataList yqdaMdataList)
    {
        Long categoryId = yqdaMdataList.getCategoryId();
        TenantCategory tenantCategory = new TenantCategory();
        String groupId = tenantCategoryMapper.selectGroupIdById(categoryId, tenantCategory.getTableName());
        if(!StringUtils.isNotEmpty(groupId)){
            throw new ServiceException("请选择元数据方案");
        }
        yqdaMdataList.setGroupId(Long.valueOf(groupId));
        PageUtils.startPage();
        List<TenantMdataList> tenantMdataLists = tenantCateMdataListMapper.selectTenantMdataListList(yqdaMdataList);
        return tenantMdataLists;
    }

    /**
     * 新增元数据明细
     * @return 结果
     */
    @Override
    @Transactional
    public int insertYqdaMdataList(String ids,Long categoryId,Integer typeFields) throws SQLException {
        String tenantCode = SecurityUtils.getTenantCode();
        TenantCategory tenantCategory = new TenantCategory();
        TenantCategory tenantCategory1 = tenantCategoryMapper.selectTenantCategoryByID(categoryId, tenantCategory.getTableName());
        Long groupId = tenantCategory1.getGroupId();

        ArrayList<TenantMdataList> tenantMdataLists = new ArrayList<>();
        TenantFields fields = new TenantFields();
        fields.setIds(ids);
        fields.setType(String.valueOf(typeFields));
        List<TenantFields> yqFieldsList = tenantFieldsMapper.selectTenantFieldsList(fields);
        Connection conn = null;
        Statement stmt = null;
        try {
            conn = dataSource.getConnection();
            conn.setAutoCommit(false);//启动事务
            stmt = conn.createStatement();
            for(TenantFields data: yqFieldsList){
                //添加元数据明细
                TenantMdataList mDataList = new TenantMdataList();
                mDataListSetFields(mDataList,data,groupId);
                tenantMdataLists.add(mDataList);
                tenantCateMdataListMapper.insertTenantMdataList(mDataList);
            }
            //更新主表（电子文件没有主表）
            //Integer type = tenantCategory1.getType();
            if(2!=typeFields){
                String mainTableSql = tenantCategoryService.updateMainTableSql(tenantMdataLists, tenantCode,typeFields);//获取更新主表sql
                if(StringUtils.isNotEmpty(mainTableSql)) {
                    if(mainTableSql.endsWith(";")) mainTableSql = mainTableSql.substring(0,mainTableSql.length()-1);
                    String[] split = mainTableSql.split(";");
                    for(int i=0;i<split.length;i++){
                        //tenantCategoryMapper.updateMainTableCol(split[i]); //更新主表
                        stmt.execute(split[i]);
                    }
                }
            }
            //更新分表
            String subTableSql = subTableSql(tenantMdataLists, typeFields, tenantCategory1);
            if(StringUtils.isNotEmpty(subTableSql)) {
                if(subTableSql.endsWith(";")) subTableSql = subTableSql.substring(0,subTableSql.length()-1);
                String[] split = subTableSql.split(";");
                for(int i=0;i<split.length;i++){
                    //tenantCategoryMapper.updateMainTableCol(split[i]);
                    stmt.execute(split[i]);
                }
            }
            conn.commit();//提交事务
        } catch (SQLException e) {
            conn.rollback();
            e.printStackTrace();
        }finally {
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        }
        return 1;
    }

    public String subTableSql(List<TenantMdataList> tenantMdataLists, Integer type, TenantCategory tenantCategory){
        String tableName = 0==type?tenantCategory.getFileTableName():1==type?tenantCategory.getFolderTableName():2==type?
                tenantCategory.getEfileTableName():3==type?tenantCategory.getItemTableName():"";
        String allFieldOfTable = tenantCategoryMapper.getAllFieldOfTable(tableName.toUpperCase());
        List<String> colList = Arrays.asList(allFieldOfTable.split(","));
        StringBuffer sb = new StringBuffer();
        Iterator<TenantMdataList> iterator = tenantMdataLists.iterator();
        while(iterator.hasNext()){
            TenantMdataList next = iterator.next();
            String fieldName = next.getFieldName();
            if(!colList.contains(fieldName)){
                String s = tenantCategoryService.colType(next.getFieldName(), next.getFieldType(), next.getDataLength());
                sb.append("ALTER TABLE ").append(tableName.toUpperCase()).append(" ADD ").append(s).append(";");
            }
        }
        return sb.toString();
    }

    public void mDataListSetFields(TenantMdataList mDataList, TenantFields data, Long groupId){
        mDataList.setFieldCaption(data.getFieldCaption());
        mDataList.setGroupId(groupId);
        mDataList.setFieldName(data.getFieldName());
        mDataList.setFieldType(Integer.valueOf(data.getFieldType()));
        mDataList.setDataLength(Integer.valueOf(data.getFieldLength()));
        mDataList.setType(Integer.valueOf(data.getType()));
        mDataList.setShowType(Integer.valueOf(data.getShowType()));
        mDataList.setIsSystem(Integer.valueOf(data.getIsCommon()));

        mDataList.setDefaultValue(data.getDefaultVal());
        mDataList.setIsNoEmpty("true".equals(data.getNullable()) ? 0 : 1);

        //mDataList.setIsInput("true".equals(data.getNullAble()) ? 0 : 1);
        mDataList.setIsInput(0);
        mDataList.setIsUpdate(0);
        mDataList.setIsQuery(0);
        mDataList.setIsArchiveNo(0);
        // mDataList.setIsNoEmpty(0);
        mDataList.setIsHidden(0);
        mDataList.setIsExport(1);
        mDataList.setCheckChongfu(0);
        mDataList.setIsImport(0);
        mDataList.setIsMetadata(0);
        // mDataList.setShowType(4);
        mDataList.setZsfl("1");
        mDataList.setThWidth(StringUtils.isNotEmpty(data.getThWidth()) ? Integer.valueOf(data.getThWidth()):null);
        mDataList.setThAlign(data.getThAlign());
        //mDataList.setCreatorId(SecurityUtils.getUserId());
        mDataList.setCreateTime(DateUtils.getNowDate());
    }

    /**
     * 修改元数据明细
     *
     * @param yqdaMdataList 元数据明细
     * @return 结果
     */
    @Override
    @Transactional
    public int updateYqdaMdataList(TenantMdataList yqdaMdataList,String ids)
    {
        //查询是否重复
        String [] idd = ids.split(",");
        if(idd.length == 1){
            TenantMdataList select = new TenantMdataList();
            select.setGroupId(yqdaMdataList.getGroupId());
            select.setType(yqdaMdataList.getType());
            select.setFieldCaption(yqdaMdataList.getFieldCaption());
            List<TenantMdataList> mdataLists = tenantCateMdataListMapper.selectTenantMdataListListByMdataList(select);
            if(mdataLists.size() > 0 && !idd[0].equals(String.valueOf(mdataLists.get(0).getId()))){
                throw new ServiceException("元数据明细中显示名称重复！");
            }
        }
        String changefiled=yqdaMdataList.getChangefiled();//获取修改的字段
        if("isInput".equals(changefiled)||"isUpdate".equals(changefiled)||"isHidden".equals(changefiled)||"isQuery".equals(changefiled)||"isExport".equals(changefiled)){
            if(changefiled.toUpperCase().contains("QUERY")){//查询可能是精确查询到模糊查询类似,特殊处理
                if(0!=yqdaMdataList.getIsQuery()){

                }else{
                    searchandchangeapply(changefiled,yqdaMdataList.getGroupId(),yqdaMdataList.getType(),yqdaMdataList.getFieldName());
                }
            }else{
                searchandchangeapply(changefiled,yqdaMdataList.getGroupId(),yqdaMdataList.getType(),yqdaMdataList.getFieldName());
            }
        }

        return tenantCateMdataListMapper.updateTenantMdataList(yqdaMdataList,ids);
    }

    private void searchandchangeapply(String changefiled, Long groupId, Integer type,String field) {
        String realfield="";
        if("isInput".equals(changefiled)){
            if(0==type){
                realfield="JIANADDFIELD";
            }else if(1==type) {
                realfield = "JUANADDFIELD";
            }else if(2==type){
                realfield="EFILEADDFIELD";
            }else if(3==type){
                realfield="XIANGMUADDFIELD";
            }
        }else if("isUpdate".equals(changefiled)){
            if(0==type){
                realfield="JIANUPDATEFIELD";
            }else if(1==type) {
                realfield = "JUANUPDATEFIELD";
            }else if(2==type){
                realfield = "EFILEUPDATEFIELD";
            }else if(3==type){
                realfield="XIANGMUUPDATEFIELD";
            }
        }else if("isHidden".equals(changefiled)){
            if(0==type){
                realfield="JIANLISTFIELD";
            }else if(1==type) {
                realfield = "JUANLISTFIELD";
            }else if(2==type){
                realfield="EFILELISTFIELD";
            }else if(3==type){
                realfield="XIANGMULISTFIELD";
            }
        }else if("isQuery".equals(changefiled)){
            if(0==type){
                realfield="JIANQUERY";
            }else if(1==type) {
                realfield = "JUANQUERY";
            }else if(2==type){
                realfield="EFILEQUERY";
            }else if(3==type){
                realfield="XIANGMUQUERY";
            }
        }else if("isExport".equals(changefiled)){
            if(0==type){
                realfield="JIANEXPORTFIELD";
            }else if(1==type) {
                realfield = "JUANEXPORTFIELD";
            }else if(2==type){
                realfield="EFILEEXPORTFIELD";
            }else if(3==type){
                realfield="XIANGMUEXPORTFIELD";
            }
        }
        List<Map<String,Object>> applystringlist=tenantApplyMapper.getstringforchange(groupId,realfield,new TenantApply().getTableName(),new TenantCategory().getTableName());
        if(null==applystringlist||applystringlist.size()==0){

        }else{
            for(Map applymap:applystringlist){
                boolean had=false;
                String applystring=(String)applymap.get(realfield);
                Long id=(Long)applymap.get("ID");
                if(null==applystring||"".equals(applystring)){
                    continue;
                }
                String[] fields=applystring.split(",");
                List<String> list=new ArrayList<>(fields.length);
                for (int i = 0; i < fields.length; i++) {
                    if(field.equals(fields[i])){
                        had=true;
                    }else{
                        list.add(fields[i]);
                    }
                }
                if(had){
                    tenantApplyMapper.updateYqdaApplyModelbygroupid(id,realfield,String.join(",",list),new TenantApply().getTableName());
                }
            }

        }
    }

    /**
     * 批量删除元数据明细
     *
     * @param ids 需要删除的元数据明细主键
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int deleteYqdaMdataListByIds(Long[] ids,Long categoryId,Integer type) throws SQLException {
        TenantCategory tenantCategory = new TenantCategory();
        TenantCategory tenantCategory1 = tenantCategoryMapper.selectTenantCategoryByID(categoryId, tenantCategory.getTableName());
        TenantMdataList tenantMdataList = new TenantMdataList();
        String idsStr = Arrays.toString(ids);
        idsStr = idsStr.replaceAll("\\[","").replaceAll("]","");
        tenantMdataList.setIds(idsStr);
        List<TenantMdataList> tenantMdataLists = tenantCateMdataListMapper.selectTenantMdataListList(tenantMdataList);
        String dropSql = getDropSql(tenantMdataLists, tenantCategory1, type);
        String[] split = dropSql.split(";");
        Connection conn = null;
        Statement stmt = null;
        try{
            conn = dataSource.getConnection();
            conn.setAutoCommit(false);//启动事务
            stmt = conn.createStatement();
            for(int i=0;i<split.length;i++){
                //tenantCategoryMapper.updateMainTableCol(split[i]);
                stmt.execute(split[i]);
            }
            conn.commit();
        }catch (SQLException e){
            conn.rollback();
            e.printStackTrace();
        }finally {
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        }
        String tableName = tenantMdataList.getTableName();
        return tenantCateMdataListMapper.deleteTenantMdataListByIds(ids,tableName);
    }

    public String getDropSql(List<TenantMdataList> tenantMdataLists, TenantCategory tenantCategory, Integer type){
        StringBuffer sb = new StringBuffer();
        String tableName = 0==type?tenantCategory.getFileTableName():1==type?tenantCategory.getFolderTableName():2==type?
                tenantCategory.getEfileTableName():3==type?tenantCategory.getItemTableName():"";
        Iterator<TenantMdataList> iterator = tenantMdataLists.iterator();
        while (iterator.hasNext()){
            TenantMdataList next = iterator.next();
            String fieldName = next.getFieldName();
            sb.append("ALTER TABLE ").append(tableName).append(" DROP COLUMN ").append(fieldName).append(";");
        }
        return sb.toString();
    }
    /**
     * 删除元数据明细信息
     *
     * @param id 元数据明细主键
     * @return 结果
     */
    @Override
    public int deleteYqdaMdataListById(Long id)
    {
        TenantMdataList tenantMdataList = new TenantMdataList();
        String tableName = tenantMdataList.getTableName();
        return tenantCateMdataListMapper.deleteTenantMdataListById(id,tableName);
    }

    @Override
    public List<TenantFields> getGroupDataList(TenantFields yqfields, Long groupId) {
        TenantMdataList tenantMdataList = new TenantMdataList();
        String tableName = tenantMdataList.getTableName();
        Integer type = Integer.valueOf(yqfields.getType());
        return tenantFieldsMapper.getGroupDataList(yqfields,type,groupId,tableName);
    }

    @Override
    public String copyIsRepeat(String ids, Long groupId,Integer type) {
        TenantMdataList tenantMdataList = new TenantMdataList();
        String tableName = tenantMdataList.getTableName();
        String msg = tenantCateMdataListMapper.copyIsRepeat(ids,groupId,type,tableName);
        return msg;
    }

    @Override
    @Transactional
    public int copyToGroup(String ids, Long groupId, Integer type) {
        TenantMdataList tenantMdataList = new TenantMdataList();
        String tableName = tenantMdataList.getTableName();
        List<TenantMdataList> dataLists = tenantCateMdataListMapper.getDataListsByIds(ids,tableName);
        for(TenantMdataList data:dataLists){
            TenantMdataList num = tenantCateMdataListMapper.isExist(data.getFieldName(),groupId,data.getType(),tableName);
            if(num != null && type == 1){
                //覆盖
                data.setId(num.getId());
                data.setGroupId(groupId);
                data.setTableName(tableName);
                tenantCateMdataListMapper.updateTenantMdataList(data,String.valueOf(num.getId()));
            }else if(num != null && type == 2){
                //跳过
                continue;
            }else {
                data.setId(null);
                data.setGroupId(groupId);
                data.setTableName(tableName);
                tenantCateMdataListMapper.insertTenantMdataList(data);
            }
        }
        return 0;
    }

    @Override
    @Transactional
    public void importHddaMDataList(List<TenantMdataList> dataLists, Long groupId, Integer type) {
        TenantMdataList tenantMdataList = new TenantMdataList();
        String tableName = tenantMdataList.getTableName();
        for(TenantMdataList data:dataLists){
            TenantMdataList num = tenantCateMdataListMapper.isExist(data.getFieldName(),groupId,data.getType(),tableName);
            if(num != null && type == 1){
                //覆盖
                data.setId(num.getId());
                data.setGroupId(groupId);
                data.setTableName(tableName);
                tenantCateMdataListMapper.updateTenantMdataList(data,String.valueOf(num.getId()));
            }else if(num != null && type == 2){
                //跳过
                continue;
            }else {
                data.setId(null);
                data.setGroupId(groupId);
                data.setTableName(tableName);
                tenantCateMdataListMapper.insertTenantMdataList(data);
            }
        }
    }

    @Override
    public List<Map<String, String>> getshowfield(JSONObject json) {

        String databaseId =  yqDatabaseIdProvider.getDatabaseId();

        if(null==json.getString("level")||"".equals(json.getString("level"))){
            throw new ServiceException("level is null");
        }
        int mdatatype = -1;
        if("jian".equals(json.getString("level"))){
            mdatatype=0;
        }else if("juan".equals(json.getString("level"))) {
            mdatatype = 1;
        }else if("efile".equals(json.getString("level"))){
            mdatatype=2;
        }else if("xiangmu".equals(json.getString("level"))){
            mdatatype=3;
        }
        TenantMdataList tenantMdataList=new TenantMdataList();
        String mdataListTableName=tenantMdataList.getTableName();
        TenantCategory tenantCategory=new TenantCategory();
        String categorytableName=tenantCategory.getTableName();
        TenantApply tenantApply=new TenantApply();
        String applyTableName=tenantApply.getTableName();
        if(null!=json.getInteger("type")){//当前层级全部门类
            TenantTablehead tablehead=new TenantTablehead();
            tablehead.setTablemenuId(json.getLong("menuId"));
            tablehead.setZltype(json.getInteger("type"));
            tablehead.setQzh(json.getString("qzh"));
            String insql="";
            String ordersql="";
            String isall=json.getString("isall");
            if("true".equals(isall)){

            }else{
                String gethead = wenjianhuishouzhanmapper.gethead(tablehead);
                if(null!=gethead&&!"".equals(gethead)){
                    insql="and field_name in('"+gethead.replace(",","','").replace(" DESC","").replace(" ASC","").replace(" NONE","")+"')";
                    if(databaseId.equalsIgnoreCase(DbIdEnum.OSCAR.getCode()) || databaseId.equalsIgnoreCase(DbIdEnum.KINGBASE.getCode())){
                        gethead = gethead.replace(" DESC","").replace(" ASC","").replace(" NONE","");
                        ordersql=" order by "+ YqDatabaseSQLUtil.YQ_INSTR(gethead,"FIELD_NAME")+"";
                    }else if(databaseId.equalsIgnoreCase(DbIdEnum.DM.getCode())){
                        gethead=gethead.replace(",","','").replace(" DESC","").replace(" ASC","").replace(" NONE","");
                       if(!gethead.endsWith("'")){
                           gethead+="'";
                       }
                       if(!gethead.startsWith("'")){
                           gethead="'"+gethead;
                       }
                        ordersql=" order by "+ YqDatabaseSQLUtil.YQ_INSTR(gethead,"FIELD_NAME");

                    }else {
                        ordersql=" order by '"+ YqDatabaseSQLUtil.YQ_INSTR(gethead,"FIELD_NAME").replace(",","','").replace(" DESC","").replace(" ASC","").replace(" NONE","")+"'";
                    }
                }
            }
            return tenantCateMdataListMapper.getshowfieldbytype(json.getInteger("type"),mdatatype,categorytableName,mdataListTableName,insql,ordersql);
        }else{//指定门类
            if(null==json.getLong("categoryId")){
                throw new ServiceException("categoryId is null");
            }
            if(null==json.getLong("menuId")){
                throw new ServiceException("menuId is null");
            }
            String applyString= tenantCateMdataListMapper.getshowfieldbyapply(json.getLong("categoryId"),json.getLong("menuId"),json.getString("level").toUpperCase()+"LISTFIELD",applyTableName);
            String orderby=" order by ";
            if(null!=applyString&&!"".equals(applyString)){//如果apply中存在则使用apply中的
                String newapplyString="'" + applyString.replace(",", "','") + "'";
                String zyapplyString="";
                if(databaseId.equalsIgnoreCase(DbIdEnum.OSCAR.getCode())){
                    zyapplyString = newapplyString.replace("'","");
                }else{
                    zyapplyString = newapplyString.replace("'","&apos;");
                }
                orderby+= YqDatabaseSQLUtil.YQ_INSTR(zyapplyString,"FIELD_NAME");
                return tenantCateMdataListMapper.getshowfieldbyapply2map(json.getLong("categoryId"),categorytableName,mdataListTableName,newapplyString,mdatatype,orderby);
            }else{//如果不存在,去元数据明细中找
                orderby+=" ORDER_NO ";
                return tenantCateMdataListMapper.getshowfieldbycategoryId(json.getLong("categoryId"),mdatatype,categorytableName,mdataListTableName,orderby);
            }
        }
    }

    @Override
    public List<Map<String, String>> getqueryfield(Long categoryId, Long menuId, Integer type) {
        TenantMdataList tenantMdataList=new TenantMdataList();
        String mdataListTableName=tenantMdataList.getTableName();
        TenantCategory tenantCategory=new TenantCategory();
        String categorytableName=tenantCategory.getTableName();
        TenantApply tenantApply=new TenantApply();
        String applyTableName=tenantApply.getTableName();
        String field="";
        if(0==type){
            field="JIANQUERY";
        }else if(1==type){
            field="JUANQUERY";
        }else if(2==type){
            field="EFILEQUERY";
        }else if(3==type){
            field="XIANGMUQUERY";
        }
        String applyString= tenantCateMdataListMapper.getqueryfieldbyapply(categoryId,menuId,field,applyTableName);
        String orderby=" order by ";
        if(null!=applyString&&!"".equals(applyString)){//如果apply中存在则使用apply中的
            String newapplyString="'" + applyString.replace(",", "','") + "'";
            String zyapplyString=newapplyString.replace("'","&apos;");
            orderby+= YqDatabaseSQLUtil.YQ_INSTR(zyapplyString,"FIELD_NAME");
            return tenantCateMdataListMapper.getqueryfieldbyapply2map(categoryId,categorytableName,mdataListTableName,newapplyString,type,orderby);
        }else{//如果不存在,去元数据明细中找
            orderby+=" ORDER_NO ";
            return tenantCateMdataListMapper.getqueryfieldbycategoryId(categoryId,type,categorytableName,mdataListTableName,orderby);
        }
    }

    @Override
    public List<Map<String, String>> getexportfield(Long categoryId, Long menuId, Integer type) {
        String databaseId = sqlSessionFactory.getConfiguration().getDatabaseId();
        TenantMdataList tenantMdataList=new TenantMdataList();
        String mdataListTableName=tenantMdataList.getTableName();
        TenantCategory tenantCategory=new TenantCategory();
        String categorytableName=tenantCategory.getTableName();
        TenantApply tenantApply=new TenantApply();
        String applyTableName=tenantApply.getTableName();
        String field = "";
        if(0==type) field="jianexportfield";
        if(1==type) field="juanexportfield";
        if(2==type) field="efileexportfield";
        if(3==type) field="xiangmuexportfield";
        String applyString= tenantCateMdataListMapper.getexportfieldbyapply(categoryId,menuId,field,applyTableName);
        String orderby=" order by ";
        if(StringUtils.isNotEmpty(applyString)){
            String newapplyString="'" + applyString.replace(",", "','") + "'";
            String zyapplyString="";
            if (databaseId.equalsIgnoreCase(DbIdEnum.OSCAR.getCode())) {
                zyapplyString="STATE,"+newapplyString.replace("'","");
            } else {
                zyapplyString="&apos;STATE&apos;,"+newapplyString.replace("'","&apos;");
            }

            orderby+= YqDatabaseSQLUtil.YQ_INSTR(zyapplyString,"FIELD_NAME");
            return tenantCateMdataListMapper.getexportfieldbyapply2map(categoryId,categorytableName,mdataListTableName,newapplyString,type,orderby);
        }else{
            orderby+=" export_order_no ";
            return tenantCateMdataListMapper.getexportfieldbycategoryId(categoryId,type,categorytableName,mdataListTableName,orderby);
        }
    }

    @Override
    public String getorder(Long categoryId, Long menuId, Integer type) {
        String field="";
        if(0==type){
            field="JIANORDER";
        }else if(1==type){
            field="JUANORDER";
        }else if(2==type){
            field="EFILEORDER";
        }else if(3==type){
            field="XIANGMUORDER";
        }
        TenantApply tenantApply=new TenantApply();
        String applyTableName=tenantApply.getTableName();
        String str=tenantCateMdataListMapper.getorder(categoryId,menuId,field,applyTableName);
        if(null!=str&&!"".equals(str)){
            return str.replace("$"," ");
        }else{
            return null;
        }

    }

    @Override
    public Map<String, Object> getaddfield(Long categoryId, Long menuId, Integer type) {
        String databaseId = sqlSessionFactory.getConfiguration().getDatabaseId();
        Map<String, Object> map = new HashMap<>();
        List<Map<String, String>> data = null;
        TenantMdataList tenantMdataList=new TenantMdataList();
        String mdataListTableName=tenantMdataList.getTableName();
        TenantCategory tenantCategory=new TenantCategory();
        String categorytableName=tenantCategory.getTableName();
        TenantApply tenantApply=new TenantApply();
        String applyTableName=tenantApply.getTableName();
        String field = "";
        if(0==type) field="jianaddfield";
        if(1==type) field="juanaddfield";
        if(2==type) field="efileaddfield";
        if(3==type) field="xiangmuaddfield";
        String applyString= tenantCateMdataListMapper.getaddfieldbyapply(categoryId,menuId,field,applyTableName);
        String orderby=" order by ";
        if(StringUtils.isNotEmpty(applyString)){
            String newapplyString="'" + applyString.replace(",", "','") + "'";
            String zyapplyString="";
            if (databaseId.equalsIgnoreCase(DbIdEnum.OSCAR.getCode())) {
                zyapplyString = newapplyString.replace("'", "");
            } else {
                zyapplyString = newapplyString.replace("'", "&apos;");
            }
            orderby+= YqDatabaseSQLUtil.YQ_INSTR(zyapplyString,"FIELD_NAME");
            data = tenantCateMdataListMapper.getaddfieldbyapply2map(categoryId, categorytableName, mdataListTableName,newapplyString , type,orderby);
        }else{
            orderby+=" ORDER_NO ";
            data = tenantCateMdataListMapper.getaddfieldbycategoryId(categoryId, type, categorytableName, mdataListTableName,orderby);
        }
        TenantMdataGroup group = groupMapper.getMdataGroupByCategoryId(categoryId, new TenantMdataGroup().getTableName(),new TenantCategory().getTableName());
        map.put("addColumn", data);
        if(type==0) map.put("colLength",group.getWjColLength());
        if(type==1) map.put("colLength",group.getAjColLength());
        if(type==3) map.put("colLength",group.getXmColLength());
        return map;
    }

    @Override
    public Map<String, Object> getupdatefield(Long categoryId, Long menuId, Integer type) {
        String databaseId = sqlSessionFactory.getConfiguration().getDatabaseId();
        Map<String, Object> map = new HashMap<>();
        List<Map<String, String>> data = null;
        TenantMdataList tenantMdataList=new TenantMdataList();
        String mdataListTableName=tenantMdataList.getTableName();
        TenantCategory tenantCategory=new TenantCategory();
        String categorytableName=tenantCategory.getTableName();
        TenantApply tenantApply=new TenantApply();
        String applyTableName=tenantApply.getTableName();
        String field = "";
        if(0==type) field="jianupdatefield";
        if(1==type) field="juanupdatefield";
        if(2==type) field="efileupdatefield";
        if(3==type) field="xiangmuupdatefield";
        String applyString= tenantCateMdataListMapper.getupdatefieldbyapply(categoryId,menuId,field,applyTableName);
        String orderby=" order by ";
        if(StringUtils.isNotEmpty(applyString)){
            String newapplyString="'" + applyString.replace(",", "','") + "'";
            String zyapplyString="";
            if (databaseId.equalsIgnoreCase(DbIdEnum.OSCAR.getCode())) {
                zyapplyString="STATE,"+newapplyString.replace("'","");
            } else {
                zyapplyString="&apos;STATE&apos;,"+newapplyString.replace("'","&apos;");
            }

            orderby+= YqDatabaseSQLUtil.YQ_INSTR(zyapplyString,"FIELD_NAME");
            data = tenantCateMdataListMapper.getupdatefieldbyapply2map(categoryId, categorytableName, mdataListTableName, newapplyString, type,orderby);
        }else{
            orderby+=" ORDER_NO ";
            data = tenantCateMdataListMapper.getupdatefieldbycategoryId(categoryId, type, categorytableName, mdataListTableName,orderby);
        }
        TenantMdataGroup group = groupMapper.getMdataGroupByCategoryId(categoryId, new TenantMdataGroup().getTableName(),new TenantCategory().getTableName());
        map.put("updateColumn", data);
        if(type==0) map.put("colLength",group.getWjColLength());
        if(type==1) map.put("colLength",group.getAjColLength());
        if(type==3) map.put("colLength",group.getXmColLength());
        return map;
    }

    @Override
    public List<TenantRelevance> getrelevancelist(JSONObject json) {
        TenantRelevance relevance=new TenantRelevance();
        relevance.setFieldName(json.getString("field"));
        relevance.setFieldLevel(json.getInteger("fieldlevel"));
        relevance.setFieldType(json.getInteger("fieldtype"));
        relevance.setGroupId(json.getLong("groupId"));
        return tenantCateMdataListMapper.getrelevancelist(relevance);
    }

    @Override
    public List<Map<String, Object>> getrelevancefield(JSONObject json) {
        String field=json.getString("field");
        Integer nowlevel=json.getInteger("nowlevel");
        Integer relelevel=json.getInteger("relelevel");
        Integer fieldtype=json.getInteger("fieldtype");
        Long groupId=json.getLong("groupId");
        String noequals="";
        if(relelevel==nowlevel){
            noequals=" and FIELD_NAME!='"+field+"'";
        }
        return tenantCateMdataListMapper.getrelevancefield(field,nowlevel,relelevel,fieldtype,groupId,new TenantMdataList().getTableName(),new TenantRelevance().getTableName(),noequals);
    }

    @Override
    public int addrelevance(JSONObject json) {
        String field=json.getString("field");
        String relefield=json.getString("relefield");
        Integer nowlevel=json.getInteger("nowlevel");
        Integer relelevel=json.getInteger("relelevel");
        Integer fieldtype=json.getInteger("fieldtype");
        Integer relefieldtype=json.getInteger("relefieldtype");
        Integer relation=json.getInteger("relation");
        Long groupId=json.getLong("groupId");
        TenantRelevance relevance=new TenantRelevance();
        relevance.setCreateDate(DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"));
        relevance.setCreator(SecurityUtils.getLoginUser().getUserId());
        relevance.setFieldName(field);
        relevance.setFieldType(fieldtype);
        relevance.setFieldLevel(nowlevel);
        relevance.setReleField(relefield);
        relevance.setRelefieldType(relefieldtype);
        relevance.setRelefieldLevel(relelevel);
        relevance.setGroupId(groupId);
        relevance.setRelation(relation);
        return tenantCateMdataListMapper.addrelevance(relevance);
    }

    @Override
    public TenantRelevance getreledetail(Long id) {
        return tenantCateMdataListMapper.getreledetail(new TenantRelevance().getTableName(),id);
    }

    @Override
    public int editrele(TenantRelevance relevance) {
        //TODO 判断是否有重复
        int i=tenantCateMdataListMapper.gethadcount(relevance);
        if(i>0){
            throw new RuntimeException("和已有关联重复!修改失败");
        }
        relevance.setUpdater(SecurityUtils.getLoginUser().getUserId());
        relevance.setUpdateDate(DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"));
        return tenantCateMdataListMapper.editrele(relevance);
    }

    @Override
    public int delterele(JSONObject json) {
        List ids=json.getJSONArray("ids");
        return tenantCateMdataListMapper.delterele(new TenantRelevance().getTableName(),ids);
    }

    @Override
    public List<Map<String, Object>> getrelevanceforadd(JSONObject json) {
        Long categoryId=json.getLong("categoryId");
        Integer level=json.getInteger("level");
        Long itemId=json.getLong("itemId");
        Long folderId=json.getLong("folderId");
        TenantCategory category = tenantCategoryService.selectTenanCategoryByID(categoryId);
        List<Map<String,Object>> relelist=tenantCateMdataListMapper.getrelelist(category.getGroupId(),level,new TenantRelevance().getTableName());//获取所有关联
        List<String> listxm=new ArrayList<>(relelist.size());//用于存储项目关联
        List<String> listjuan=new ArrayList<>(relelist.size());//用于存储卷关联
        List<String> listjian=new ArrayList<>(relelist.size());//用于存储件关联
        List<Map<String,Object>> returnlist=new ArrayList(relelist.size());
        if(relelist.size()>0){
            for (int i = 0; i < relelist.size(); i++) {
                if("3".equals(String.valueOf(relelist.get(i).get("FIELD_LEVEL")))){
                    listxm.add((String)relelist.get(i).get("FIELD_NAME"));
                }else if("1".equals(String.valueOf(relelist.get(i).get("FIELD_LEVEL")))){
                    listjuan.add((String)relelist.get(i).get("FIELD_NAME"));
                }else if("0".equals(String.valueOf(relelist.get(i).get("FIELD_LEVEL")))){
                    listjian.add((String)relelist.get(i).get("FIELD_NAME"));
                }
            }
            Map<String,String> xmmap=new HashMap<>(listxm.size());//用于存储项目字段值
            Map<String,String> juanmap=new HashMap<>(listjuan.size());//用于案卷项目字段值
            Map<String,String> jianmap=new HashMap<>(listjian.size());//用于件项目字段值
            if (listxm.size()>0){
                if (level==3){//同层不处理

                }else{
                    xmmap=tenantCateMdataListMapper.getfieldvaluerele(itemId,category.getItemTableName(),listxm);//获取值
                }
            }
            if(listjuan.size()>0){
                if (level==1){//同层不处理

                }else{
                    juanmap=tenantCateMdataListMapper.getfieldvaluerele(folderId,category.getFolderTableName(),listjuan);//获取值
                }
            }
            if(listjian.size()>0){
                    //同层不处理
                jianmap.keySet().forEach(key -> jianmap.put(key, null));
            }

            //处理返回,上上层优先级小于上层优先级  同层不做处理
            for (int i = 0; i < relelist.size(); i++) {
                Map returnmap=new HashMap(relelist.size());
                if(null!=xmmap){
                    if(xmmap.containsKey(relelist.get(i).get("FIELD_NAME"))){
                        returnmap.put("FIELDNAME", relelist.get(i).get("RELE_FIELD"));
                        returnmap.put("VALUE",xmmap.get(relelist.get(i).get("FIELD_NAME")));
                        returnmap.put("RELATION",relelist.get(i).get("RELATION"));
                        returnmap.put("FROMLEVEL",relelist.get(i).get("FIELD_LEVEL"));
                    }
                }
                if(null!=juanmap){
                    if(juanmap.containsKey(relelist.get(i).get("FIELD_NAME"))){
                        returnmap.put("FIELDNAME", relelist.get(i).get("RELE_FIELD"));
                        returnmap.put("VALUE",juanmap.get(relelist.get(i).get("FIELD_NAME")));
                        returnmap.put("RELATION",relelist.get(i).get("RELATION"));
                        returnmap.put("FROMLEVEL",relelist.get(i).get("FIELD_LEVEL"));
                    }
                }
                if(null!=jianmap){
                    if(jianmap.containsKey(relelist.get(i).get("RELE_FIELD"))){
                        returnmap.put("FIELDNAME", relelist.get(i).get("RELE_FIELD"));
                        returnmap.put("VALUE",jianmap.get(relelist.get(i).get("FIELD_NAME")));
                        returnmap.put("RELATION",relelist.get(i).get("RELATION"));
                        returnmap.put("FROMLEVEL",relelist.get(i).get("FIELD_LEVEL"));
                    }
                }

                returnlist.add(returnmap);
            }
        }
        return returnlist;
    }

    @Override
    public List<TenantMdataList> getFileNumberField(Long categoryId) {
        TenantCategory tenantCategory = new TenantCategory();
        String groupId = tenantCategoryMapper.selectGroupIdById(categoryId, tenantCategory.getTableName());
        TenantMdataList tenantMdataList = new TenantMdataList();
        tenantMdataList.setIsArchiveNo(1);
        tenantMdataList.setGroupId(Long.valueOf(groupId));
        tenantMdataList.setType(0);
        List<TenantMdataList> list = tenantCateMdataListMapper.selectTenantMdataListList(tenantMdataList);
        return list;
    }

    @Override
    @Transactional
    public int batchUpdateYqdaMdataList(TenantMdataList yqdaMdataList, String ids) {

        //查询是否重复
        String[] idd = ids.split(",");

        String changefiled = yqdaMdataList.getChangefiled();//获取修改的字段
        if ("isInput".equals(changefiled) || "isUpdate".equals(changefiled) || "isHidden".equals(changefiled) || "isQuery".equals(changefiled) || "isExport".equals(changefiled)) {
            if (changefiled.toUpperCase().contains("QUERY")) {//查询可能是精确查询到模糊查询类似,特殊处理
                if (0 != yqdaMdataList.getIsQuery()) {

                } else {
                    searchandchangeapply(changefiled, yqdaMdataList.getGroupId(), yqdaMdataList.getType(), yqdaMdataList.getFieldName());
                }
            } else {
                searchandchangeapply(changefiled, yqdaMdataList.getGroupId(), yqdaMdataList.getType(), yqdaMdataList.getFieldName());
            }
        }

        return tenantCateMdataListMapper.updateTenantMdataList(yqdaMdataList, ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean moveDown(Long metadataListIds, Long groupId, Long categoryId, Integer type) {
        boolean reutrnVal = true;
        TenantMdataList tenantMdataList=new TenantMdataList();
        StringBuilder moveDownSql = new StringBuilder();
        String orderNoString = tenantCateMdataListMapper.getSingle("SELECT ORDER_NO FROM "+tenantMdataList.getTableName()+" WHERE ID="+metadataListIds);
        List<Map<String, String>> orderNoMapList = tenantCateMdataListMapper.getListResult1("SELECT ID,ORDER_NO FROM "+tenantMdataList.getTableName()+" WHERE GROUP_ID="+groupId+" AND TYPE="+type+" ORDER BY ORDER_NO");
        String nextId = "";
        String nextOrderNo = "";
        for(int i=0;i<orderNoMapList.size();i++) {
            if (orderNoString!=null && orderNoMapList.get(i).get("ORDER_NO")!=null) {
                if (orderNoString.equals(orderNoMapList.get(i).get("ORDER_NO"))) {
                    nextId = orderNoMapList.get(i+1).get("ID");
                    nextOrderNo = orderNoMapList.get(i+1).get("ORDER_NO");
                    break;
                }
            }else {
                return reutrnVal;
            }
        }

        moveDownSql.append("UPDATE "+tenantMdataList.getTableName()+" SET ORDER_NO="+nextOrderNo+" WHERE ID="+metadataListIds+";UPDATE "+tenantMdataList.getTableName()+" SET ORDER_NO="+orderNoString+" WHERE ID="+nextId);
        tenantCateMdataListMapper.excu(moveDownSql.toString());
        return reutrnVal;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean moveUp(Long metadataListIds, Long groupId, Long categoryId, Integer type) {
        boolean reutrnVal = true;
        StringBuilder moveUpSql = new StringBuilder();
        TenantMdataList tenantMdataList=new TenantMdataList();
        String orderNoString = tenantCateMdataListMapper.getSingle("SELECT ORDER_NO FROM "+tenantMdataList.getTableName()+" WHERE ID="+metadataListIds);
        List<Map<String, String>> orderNoMapList = tenantCateMdataListMapper.getListResult1("SELECT ID,ORDER_NO FROM "+tenantMdataList.getTableName()+" WHERE GROUP_ID="+groupId+" AND TYPE="+type+" ORDER BY ORDER_NO");
        String preId = "";
        String preOrderNo = "";
//			从数据库获取到的order_id是从1开始，所以i应该从1开始，若果为0，数据越界异常，且存在错位移动
//			for(int i=0;i<orderNoMapList.size();i++) {
        for(int i=1;i<=orderNoMapList.size();i++) {
            if (orderNoString!=null && orderNoMapList.get(i).get("ORDER_NO")!=null) {
                if (orderNoString.equals(orderNoMapList.get(i).get("ORDER_NO"))) {
                    preId = orderNoMapList.get(i-1).get("ID");
                    preOrderNo = orderNoMapList.get(i-1).get("ORDER_NO");
                    break;
                }
            }else {
                return reutrnVal;
            }
        }
        moveUpSql.append("UPDATE "+tenantMdataList.getTableName()+" SET ORDER_NO="+preOrderNo+" WHERE ID="+metadataListIds+";UPDATE "+tenantMdataList.getTableName()+" SET ORDER_NO="+orderNoString+" WHERE ID="+preId);
        tenantCateMdataListMapper.excu(moveUpSql.toString());
        return reutrnVal;
    }
}
